package com.qiku.runner;

import com.qiku.entity.Article;
import com.qiku.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *在应用启动的时候把博客浏览量更新到redis中
 */
@Component
public class ViewCountRunner implements CommandLineRunner {
    @Autowired
    private ArticleService articleService;
    @Autowired
    @Resource(name = "redisStringTemplate")
    private RedisTemplate redisTemplate;
    @Override
    public void run(String... args) throws Exception {
        //查询博客信息  id  ViewCount
        List<Article> articleList = articleService.list();
        HashMap<Long, Integer> viewCountMap = new HashMap<>();
        for (Article article : articleList) {
            viewCountMap.put(article.getId(),article.getViewCount().intValue());
        }
        //存储到redis中
        redisTemplate.opsForHash().putAll("articleViewCount",viewCountMap);
        //获取键值对  测试
        Map map = redisTemplate.opsForHash().entries("articleViewCount");
        System.out.println("redis缓存测试打印(id=viewCount)："+map);
    }
}
